<?php
/**
 * Created by Pako
 * Date: 2019/5/15
 * Time: 20:56
 */

namespace App\Repositories\Ad;


use App\Models\Ad\Ad;
use App\Models\Ad\AdPosition;
use App\Repositories\Repository;

class AdRespository extends Repository
{
    public function index($params)
    {

        $ads = Ad::query()->orderBy('created_at', 'desc')
            ->when(isset($params['position_id']), function ($query) use ($params) {
                $query->where('position_id', $params['position_id']);
            })->paginate($this->page_size, ['*'], 'page', $this->page);
        $ads = json_decode(json_encode($ads), true);

        $ps = $this->getPosition();

        if (count($ads['data'])) {
            foreach ($ads['data'] as $k => $datum) {
                $size = $ps[$datum['position_id']]['width'] . 'X' . $ps[$datum['position_id']]['height'];
                if ($ps[$datum['position_id']]['client'] == 1) {
                    $client = 'PC端';
                } else if ($ps[$datum['position_id']]['client'] == 2) {
                    $client = '移动端';
                } else {
                    $client = 'APP';
                }
                $ads['data'][$k]['position_name'] =  $client .$ps[$datum['position_id']]['title'] . $size;
            }
        }
        return $this->respondWith($ads);
    }


    public function store($data)
    {
        try {
            Ad::query()->create($data);
            return $this->respondSuccess();
        } catch (\Exception $e) {
            return $this->respondError(10110);
        }
    }

    public function save($data)
    {
        try {
            $ad = Ad::query()->find($data['ad_id']);
            $ad->fill($data)->save();
            return $this->respondSuccess();
        } catch (\Exception $e) {
            return $this->respondError(10108);
        }
    }

    public function del($ad_id)
    {
        try {
            Ad::query()->where('ad_id', $ad_id)->delete();
            return $this->respondSuccess();
        } catch (\Exception $e) {
            return $this->respondError(10108);
        }
    }

    private function getPosition()
    {
        $key = 'redis_ad_position';
        $ps = app('phpredis')->get($key);
        $ps = json_decode($ps, true);
        if (!$ps) {
            $data = AdPosition::query()->select('position_id', 'title', 'width', 'height', 'client')->where('status', 0)
                ->get();
            $ps = [];
            foreach ($data as $item) {
                $ps[$item->position_id] = $item;
            }
            app('phpredis')->setex($key, 84600, json_encode($ps));
        }
        return $ps;
    }
}